import jwt
import time
from CowProject import settings


class Mjwt:
    def __init__(self, key):
        self.key = key

    def encode(self, payload):
        try:
            # 确保payload中的所有值都是可序列化的
            print(f"Encoding payload: {payload}")
            token = jwt.encode(payload, self.key, algorithm='HS256')
            # 如果token是bytes类型，转换为字符串
            if isinstance(token, bytes):
                token = token.decode('utf-8')
            print(f"Generated token: {token}")
            return token
        except Exception as e:
            print(f"Error encoding token: {str(e)}")
            return None

    def decode(self, token):
        try:
            # 打印接收到的token用于调试
            print(f"Received token: {token}")
            
            # 检查token是否为空或格式不正确
            if not token or not isinstance(token, str):
                print(f"Invalid token format: {token}")
                return None

            # 如果token包含Bearer前缀，去掉它
            if token.startswith('Bearer '):
                token = token.split(' ')[1]
            token = token.strip()  # 移除可能的空白字符
            print(f"Token after cleaning: {token}")

            # 尝试解码
            decoded = jwt.decode(
                token,
                self.key,
                algorithms=['HS256']
            )
            
            print(f"Successfully decoded token: {decoded}")
            
            # 验证过期时间
            exp = decoded.get('exp')
            current_time = int(time.time())
            if exp and exp <= current_time:
                print(f"Token expired at {exp}, current time: {current_time}")
                return None
                
            return decoded
            
        except jwt.ExpiredSignatureError as e:
            print(f"Token expired: {str(e)}")
            return None
        except jwt.InvalidTokenError as e:
            print(f"Invalid token error: {str(e)}")
            return None
        except Exception as e:
            print(f"Unexpected error decoding JWT: {str(e)}")
            return None
    def check_token(self, token):
        return jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])

myjwt = Mjwt(settings.SECRET_KEY)